import React, { useState, useEffect, useRef } from 'react';
import { Form, Card, Input, message, Spin, Typography } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { withRouter } from 'umi';
import { getPostApplyData } from '@/pages/WorkFlow/services';
import OrgTree from '@/pages/Organization/OrgFlow/OrgTree';
import { transformAttachToArray } from '@/pages/Organization/OrgFlow/OrgTree/utils';
import { getRelativeOrganizations } from '@/pages/Organization/OrgFlow/services';
import { OrgChangeTable, CompanyEdit, DepartmentEdit } from './components';

const { Text } = Typography;

const ORGANIZATION_TYPE = {
    1: '集团',
    2: '公司',
    3: '部门',
    4: '事业部'
};

const OPERATION_TYPE = {
    0: '新增',
    1: '修改',
    2: '删除',
    3: '批量'
};

// 机构变更套件
const Organization = ({ dataSource, form, wrapperLayout, location, formValueMap = {} }) => {
    const { getFieldDecorator } = form;
    const { children: list } = dataSource;
    const hiDataId = location?.query?.hiDataId || formValueMap?.hiDataId;
    const [approveData, setApproveData] = useState(null);
    const [approveDataLoading, setApproveDataLoading] = useState(false);
    const [relativeList, setRelativeList] = useState([]);
    const [orgTreeType, setOrgTreeType] = useState([]); // 机构类型: executive 行政机构 / organization 组织机构
    const [treeChangeData, setTreeChangeData] = useState(null);
    const formRef = useRef(form);

    // 拉取审批数据
    useEffect(() => {
        if (hiDataId) {
            const fetchApproveData = async () => {
                setApproveDataLoading(true);
                const { msg, code, data } = await getPostApplyData(hiDataId);
                if (code === 10000) {
                    setApproveData(data);
                    if (data.operationType === 3) {
                        setOrgTreeType(data.compareDataField.updateInfoList[0].organizationType === 3);
                    } else {
                        setOrgTreeType(data.organizationType === 3 ? 'organization' : 'executive');
                    }
                } else {
                    message.error(msg);
                }
                setApproveDataLoading(false);
            };
            fetchApproveData();
        }
    }, [hiDataId]);

    // 获取关联机构列表
    const getRelativeList = async orgCode => {
        if (!orgCode) {
            return;
        }
        const res = await getRelativeOrganizations(orgCode);
        const { data, code } = res;
        if (code === 10000) {
            setRelativeList((Array.isArray(data) && data) || []);
        }
    };

    useEffect(() => {
        if (approveData) {
            const {
                organizationName,
                parentOrganizationPath,
                parentOrganizationCode,
                organizationPath,
                organizationType,
                operationType,
                relateOrganizationCodes = [],
                sort,
                colorCode
            } = approveData;

            // 拉取关联机构列表
            getRelativeList(parentOrganizationCode);

            // 批量机构名称摘要
            const { add: addOrg = [], delete: deleteOrg = [] } = approveData?.oldBusinessData || {};
            const batchOrgArr = [...addOrg, ...deleteOrg].map(item => item?.organizationName);
            const batchOrgNames =
                batchOrgArr?.length > 3 ? `${batchOrgArr.slice(0, 3).join('，')}...` : batchOrgArr.join('，');
            const batchOrgTypeOther = addOrg.length > 0 ? OPERATION_TYPE[0] : OPERATION_TYPE[2];
            // 由于列表操作和图形视图操作，后端说数据格式不一致不好处理，列表type使用了3批量，所以这里通过数量来显示相关文案
            const batchOrgType = batchOrgArr.length > 1 ? OPERATION_TYPE[3] : batchOrgTypeOther;

            // 摘要显示的字段
            formRef.current.setFieldsValue({
                organizationName: operationType === 3 ? batchOrgNames : organizationName, // 批量操作显示相关机构名称
                organizationType: ORGANIZATION_TYPE[organizationType],
                operationType: operationType === 3 ? batchOrgType : OPERATION_TYPE[operationType]
            });

            // 处理批量
            if (operationType === 3) {
                setTreeChangeData({ ...approveData.oldBusinessData });
            } else if (operationType !== 1) {
                // 不是编辑状态生成树追加的结构，只对单条操作有用
                const obj = {
                    add: [],
                    delete: []
                };
                const recordData = {
                    organizationName,
                    organizationPath: organizationPath || `path${Math.floor(Math.random() * (50 - 1 + 1) + 1)}`, // 新增这个服务端会修改没用，只是为了树能生成
                    organizationType,
                    parentOrganizationPath,
                    relateOrganizationCodes,
                    sort,
                    colorCode
                };
                if (operationType === 0) {
                    obj.add.push(recordData);
                } else {
                    obj.delete.push(recordData);
                }
                setTreeChangeData(obj);
            }
        }
    }, [approveData, formRef]);

    return (
        <>
            {list.map(item => {
                const { label, formId, rules, initialValue, extra } = item;
                return (
                    <Form.Item
                        label={label}
                        key={formId}
                        extra={extra}
                        style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                    >
                        {getFieldDecorator(formId, {
                            initialValue,
                            rules
                        })(<AutoRenderComponent form={form} config={item} />)}
                    </Form.Item>
                );
            })}
            <Form.Item style={{ display: 'none' }}>
                {getFieldDecorator('hiDataId', {
                    initialValue: hiDataId
                })(<Input />)}
            </Form.Item>
            <Card bordered={false} bodyStyle={{ padding: '0' }}>
                <Spin spinning={approveDataLoading}>
                    {approveData &&
                        // eslint-disable-next-line no-nested-ternary
                        (approveData?.operationType !== 1 ? (
                            <>
                                <div style={{ padding: '0 16px' }}>
                                    <OrgChangeTable data={approveData} />
                                </div>
                                <div
                                    style={{
                                        fontSize: 16,
                                        fontWeight: 'bold',
                                        height: 40,
                                        lineHeight: '40px',
                                        margin: '24px 0'
                                    }}
                                >
                                    {orgTreeType === 'executive' ? '行政机构变更图' : '组织机构变更图'}
                                </div>
                                {treeChangeData && (
                                    <OrgTree
                                        control={false}
                                        focusCurrentUser={false}
                                        showViewModeSwitch
                                        onlyTree
                                        orgTreeId={`organizationChangedFlow_${Math.floor(Math.random() * 1000000)}`}
                                        initData={approveData?.oldBusinessData?.orgList}
                                        attachData={transformAttachToArray(treeChangeData)}
                                        type={orgTreeType}
                                    />
                                )}
                            </>
                        ) : approveData?.organizationType === 3 ? (
                            <div style={{ padding: '0 16px' }}>
                                <DepartmentEdit
                                    wrapperLayout={wrapperLayout}
                                    data={approveData}
                                    relativeList={relativeList}
                                />
                            </div>
                        ) : (
                            <div style={{ padding: '0 16px' }}>
                                <CompanyEdit
                                    wrapperLayout={wrapperLayout}
                                    data={approveData}
                                    relativeList={relativeList}
                                />
                            </div>
                        ))}
                    {!approveData && (
                        <Text type="secondary">
                            会根据具体业务流程展示不同效果：新增和删除机构是表格方式展示；编辑机构是表单方式展示！流程发起后可以看到
                        </Text>
                    )}
                </Spin>
            </Card>
        </>
    );
};

export default withRouter(Organization);
